package teaching.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import teaching.exception.NotAllowException;
import teaching.mapper.StudentMapper;
import teaching.mapper.UserMapper;
import teaching.pojo.Student;
import teaching.pojo.User;
import teaching.util.JwtUtil;
import teaching.util.ThreadLocalUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:20201002983_郑雨蓓
 * Date: 2024/4/4
 * Description:
 */
@Service
public class StudentService extends ServiceImpl<StudentMapper, Student> {
    @Resource
    StudentMapper studentMapper;
    @Resource
    UserMapper userMapper;

    public String login(Student user) {
        Student dbstudent = studentMapper.findByUserName(user.getUsername());
        if (dbstudent == null) {
            throw new NotAllowException("用户名或密码错误");//自定义异常信息
        }
        if (!user.getPassword().equals(dbstudent.getPassword())) {
            throw new NotAllowException("用户名或密码错误");//自定义异常信息
        }
        //登录成功
        // 给令牌权限以后让管理员分配才行
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        String token = JwtUtil.getToken(claims);
        return token;
    }

    public int register(Student student) {
        User dbuser = userMapper.findByUserName(student.getUsername());
        if (dbuser != null) {
            throw new NotAllowException("用户名已存在");//自定义异常信息
        }
        return studentMapper.register(student);
    }

    public Student getStudentInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println("map=="+map);
        String username = (String) map.get("username");
        Student dbuser = studentMapper.findByUserName(username);
        if (dbuser == null) {
            throw new NotAllowException("用户信息存在错误");//自定义异常信息
        }
        return dbuser;
    }

    public String getStudentName(Long studentId) {
        return studentMapper.getStudentName(studentId);
    }

    public List<Student> getAllstudent() {
        return studentMapper.listAllStudent();
    }
}
